<template>
  <page-layout>
    <a-row :gutter="[10, 10]">
      <a-col :span="24">
        <a-card>
          <div class="mb-20">
            <!-- 查询参数 -->
            <pro-query
              :searchParam="state.searchParams"
              @on-search="search"
              @on-reset="reset"
            />
          </div>
          <div class="mb-10">
            <a-button type="primary" @click="handleAdd">新增</a-button>
            <a-button type="primary" class="ml-10" @click="handleExport"
              >导入课程大纲</a-button
            >
          </div>
          <!-- 列表 -->
          <a-table
            bordered
            rowKey="id"
            @change="pageOutline"
            :pagination="pagination"
            :data-source="state.dataSource"
            :columns="state.columns"
            :loading="state.loading"
            size="small"
            :scroll="{ x: 1300, y: 0 }"
          >
            <template #operation="row">
              <template v-for="(item, i) in state.operation" :key="i">
                <pro-authority :value="item.code ? item.code : false">
                  <a
                    class="separate"
                    @click="item.event(row)"
                    :style="item.label === '删除' ? 'color: #f5222d;' : ''"
                  >
                    {{ item.label }}
                  </a>
                </pro-authority>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-col>
    </a-row>
    <importModal
      :exportConfig="exportConfig"
      :visible="state.importVisible"
      @close="closeImport"
    ></importModal>
    <BasicTableModal
      v-model:visible="modalConfig.show"
      v-if="modalConfig.show"
      :columns="modalConfig.commonColumns"
      :fetchAjax="modalConfig.api"
      :title="modalConfig.title"
      :searchForm="modalConfig.searchForm"
      @selectUniversity="(value) => selectItem(value)"
    />
    <a-modal
      v-model:visible="state.uploadVisible"
      title="上传课程大纲"
      okText="关闭"
      cancelText="取消"
      @ok="handleOk"
    >
      <div style="padding: 10px 20px">
        <a-upload
          style="margin-left: 20px"
          name="files"
          accept=".zip,.xls,.xlsx,.word"
          :customRequest="handleUpload"
        >
          <a-button type="primary">
            <a-icon type="upload" />{{ t("button.upload") }}</a-button>
        </a-upload>
      </div>
    </a-modal>
    <a-modal
      v-model:visible="state.courseVisible"
      :title="state.title"
      okText="保存"
      cancelText="取消"
      @ok="handleSave"
    >
      <a-form ref="formRef" :model="state.data">
        <a-row>
          <a-col :span="16">
            <a-form-item label="课程名称" name="courseName">
              <a-input
                readonly
                v-model:value="state.data.courseName"
                :placeholder="t('placeholder.pleaseSelect')"
              >
                <template #addonAfter>
                  <div
                    class="primary-color cursor-pointer"
                    @click="handleCource"
                  >
                    {{ t("button.select") }}
                  </div>
                </template>
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item>
              <div style="padding: 10px 20px">
                <a-upload
                  style="margin-left: 20px"
                  name="files"
                  accept=".zip,.xls,.xlsx,.word"
                  :customRequest="handleUploadSin"
                >
                  <a-button type="primary">
                    <a-icon type="upload" />{{ t("button.upload") }}</a-button
                  >
                </a-upload>
              </div>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
  </page-layout>
</template>

<script setup>
import { message, modal } from "ant-design-vue";
import { page, templateUrl, imports } from "@/api/module/courseBaseInfo";
import {
  pageOutline,
  upload,
  saveOutline,
  updateOutline,
  removeOutline,
  uploadSin,
} from "@/api/module/cource-outline";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import { reactive, ref, onMounted, createVNode } from "vue";
import { useRouter } from "vue-router";
import { filterEmptyByObject } from "@/tools/common";
import importModal from "@/component/import/index.vue";
import BasicTableModal from "@/component/basic-table-modal";
import { useI18n } from "vue-i18n";

const { t } = useI18n();

const tableRef = ref(null);
const router = useRouter();

const exportConfig = reactive({
  title: "学校管理",
  exportExcel: imports,
  templateUrl: templateUrl,
  downMethod: "GET",
  fileName: "学校管理导入模板",
  params: {},
});
const modalConfig = reactive({
  title: "课程选择",
  api: page,
  show: false,
  commonColumns: [
    { dataIndex: "courseName", key: "courseName", title: "课程名称" },
    { dataIndex: "courseCode", key: "courseCode", title: "课程代码" },
    { dataIndex: "createTime", key: "createTime", title: "创建时间" },
  ],
  searchForm: [
    {
      span: 8,
      key: "courseName",
      type: "input",
      label: "课程名称",
      placeholder: "请输入",
    },
    {
      span: 8,
      key: "courseCode",
      type: "input",
      label: "课程代码",
      placeholder: "请输入",
    },
  ],
});

const state = reactive({
  dataSource: [],
  columns: [
    {
      dataIndex: "code",
      key: "code",
      title: "课程编码",
      ellipsis: true,
    },
    {
      dataIndex: "courseName",
      key: "courseName",
      title: "课程名称",
      ellipsis: true,
    },
    {
      dataIndex: "courseCode",
      key: "courseCode",
      title: "课程代码",
      ellipsis: true,
    },
    {
      dataIndex: "schName",
      key: "schName",
      title: "学校名称",
      ellipsis: true,
    },
    {
      dataIndex: "outlineFileName",
      key: "outlineFileName",
      title: "课程大纲",
      ellipsis: true,
    },
    {
      dataIndex: "operation",
      key: "operation",
      title: "操作",
      width: 120,
      slots: {
        customRender: "operation",
      },
    },
  ],
  searchParams: [
    {
      span: 4,
      key: "courseName",
      type: "input",
      label: "课程名称",
      placeholder: "请输入",
    },
  ],
  operation: [
    {
      label: "编辑",
      event: async ({ record }) => {
        state.data = { ...record }
        state.title = '编辑课程大纲'
        state.courseVisible = true;
      },
    },
    {
      label: "删除",
      event: async ({ index, record }) => {
        modal.confirm({
          title: "您是否确定要删除此数据?",
          icon: createVNode(ExclamationCircleOutlined),
          okText: "确定",
          cancelText: "取消",
          onOk() {
            if (record.id) {
              removeOutline({ id: record.id }).then((res) => {
                if (res.success) getPage();
              });
            } else {
              state.dataSource.filter((v, i) => i != index);
            }
          },
        });
      },
    },
  ],
  loading: false,
  param: {},
  pagination: {
    pageNum: 1,
    pageSize: 10,
    total: 0,
  },
  uploadVisible: false,
  courseVisible: false,
  currentRow: {},
  dataIdx: null,
  data: {
    courseOnlyCode: '',
    courseOnlyShiftCode: "",
    outlineFileUrl: "",
    outlineFileName: "",
    id: "",
    courseName: "",
    courseCode: "",
    schName: "",
  },
  title: '添加课程大纲'
});

const search = function (value) {
  state.param = {
    ...state.param,
    ...filterEmptyByObject(value),
    ...state.pagination,
  };
  getPage();
};
const reset = function () {
  state.param = {
    ...state.pagination,
  };
  getPage();
};
const handleCource = () => {
  modalConfig.show = true;
};
const handleAdd = () => {
  state.title = '添加课程大纲'
  state.courseVisible = true;
};
const selectItem = (value) => {
  if (value) {
    state.data = {
      ...state.data,
      courseOnlyCode: value.courseOnlyCode,
      courseOnlyShiftCode: "",
      outlineFileUrl: "",
      outlineFileName: "",
      id: "",
      courseName: value.courseName,
      courseCode: value.courseCode,
      schName: value.schName,
    }
  }
  console.log(value);
};
const handleOk = () => {
  state.uploadVisible = false;
};
const handleSave = () => {
  state.uploadVisible = false;
  saveForm(state.data)
};
const handleExport = () => {
  state.uploadVisible = true;
};
const closeImport = (value) => {
  state[value] = false;
  tableRef.value.reload();
};
const getPage = async () => {
  state.loading = true;
  let response = await pageOutline({ ...state.param });
  if (response.success && response.data.record) {
    state.loading = false;
    state.dataSource = response.data.record.map((item) => {
      console.log("item.courseCode: ", item.courseCode);
      return {
        ...item,
        ...item.courseCode,
      };
    });
    state.pagination.total = response.data.total;
  }
};
const handleUpload = (data, type) => {
  const formData = new FormData();
  formData.append("file", data.file);
  upload(formData)
    .then((res) => {
      if (!res.success) {
        message.error({ content: "导入失败" });
        data.onError();
      } else if (res.success && res.data) {
        data.onSuccess(res.data);
        message.success({ content: "导入成功" });
      }
    })
    .finally(() => {
      state.isLoading = false;
    });
};
const handleUploadSin = (data, type) => {
  const formData = new FormData();
  formData.append("file", data.file);
  uploadSin(formData)
    .then((res) => {
      if (!res.success) {
        state.currentRow.outlineFileName = data.file.name || "";
        message.error({ content: "导入失败" });
        data.onError();
      } else if (res.success && res.data) {
        data.onSuccess(res.data);
        state.data.outlineFileUrl = res.data.path || "";
        state.data.outlineFileName = res.data.name || "";
        message.success({ content: "导入成功" });
      }
    })
    .finally(() => {
      state.isLoading = false;
    });
};
const saveForm = async(record) => {
  let response = null;
  if (record.id) {
    response = await updateOutline({ ...record });
  } else {
    response = await saveOutline({ ...record });
  }
  if (!response.success) return message.error("保存失败");
  message.success("保存成功");
  state.courseVisible = false
  getPage();
}
onMounted(() => {
  state.param = {
    ...state.pagination,
  };
  getPage();
});
</script>
<style lang="less" scoped>
.separate {
  padding: 5px;
}
</style>
